package utils.enumerate;

import utils.string.StringUtils;

/**
 * UNKNOWN(0, "未知枚举")</br>
 * CAT(1, "猫")</br>
 * DOG(2, "狗").
 *
 * @author zhangbo
 * @since 1.0.0
 */
public enum DemoEnum {
    UNKNOWN(0, "未知枚举"), CAT(1, "猫"), DOG(2, "狗");

    private int code;
    private String description;

    private DemoEnum(int code, String description) {
        this.code = code;
        this.description = description;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    // often use utils
    /**
     * find a enum by it's name.
     *
     * @param enumName
     *            name of enum
     * @return if find, will return enum; otherwise will return
     *         {@link utils.enumerate.DemoEnum}.UNKNOWN
     * @author zhangbo
     * @since 1.0.0
     */
    public static DemoEnum parse(String enumName) {
        if (StringUtils.isNotEmpty(enumName)) {
            for (DemoEnum item : values()) {
                if (enumName.equals(item.name())) {
                    return item;
                }
            }
        }
        return DemoEnum.UNKNOWN;
    }

    /**
     * In the filters, we would use enum as value. However most of the time, we
     * store code in mysql, so we should transfer enum to it's code. For
     * example:
     * 
     * <pre>
     * animal=DOG ==> animal=2
     * </pre>
     * 
     * @param filters
     *            filters
     * @return transfer enum to it's code
     * @author zhangbo
     * @since 1.0.0
     */
    public static String transfer(String filters) {
        if (filters != null) {
            String result = filters;
            for (DemoEnum val : values()) {
                if (filters.contains("=" + val.name())) {
                    result = result.replace("=" + val.name(), "=" + val.getCode());
                }
            }
            return result;
        } else {
            return filters;
        }
    }
}
